#include "handlemplayer.h"
#include <QProcess>
#include <QDebug>
#include <QTimer>


HandleMplayer::HandleMplayer(QObject *parent) :
    QObject(parent)
{
    appsHome = "/home/manu/QT/sources/cloud/googleSrc/socialwebmediacenter/KdeadMouse/apps/youtube";
    this->innerProcess = new QProcess(this);
    this->refreshTimer = new QTimer(this);
    //connect Signals
    this->innerProcess->setProcessChannelMode(QProcess::MergedChannels);
    connect(innerProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(readyToRead()));
    connect(innerProcess,SIGNAL(readyReadStandardError()),this,SLOT(readyToReadError()));
    connect(innerProcess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(processFinished(int, QProcess::ExitStatus)));
    connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refreshPosition()));
}


HandleMplayer::~HandleMplayer()
{
    innerProcess->kill();
    qDebug()<<"killing proc";
    delete innerProcess;
    delete refreshTimer;
}


void HandleMplayer::relativeSeek(int seconds){
    this->sendOrder("seek " + QString(seconds));
}

void HandleMplayer::pause(){
    this->sendOrder("pause");
}
void HandleMplayer::startVideo(QString videoId){
    this->videoIdToLoad=videoId;
    if(QProcess::NotRunning == innerProcess->state()){
        this->startProcess();
        return;
    }
    this->sendOrder("quit");
}

void HandleMplayer::startProcess(){
    //ex : mplayer -slave -quiet -wid idInnerWin -cookies -cookies-file ${COOKIE_FILE} $(youtube-dl -g --cookies ${COOKIE_FILE} $*)
    // p_args = -cookies -cookies-file ${COOKIE_FILE} $(youtube-dl -g --cookies ${COOKIE_FILE} $*)

    qDebug()<<"start with videoIdToLoad:" << videoIdToLoad << " , videoIdLoading:" << videoIdLoading;

    if(videoIdToLoad.isEmpty()){
        qDebug()<<"rien à lire";
        return;
    }
    qDebug()<<"launch process";
    QString cmd = appsHome + "/bin/tube.sh";
    QStringList args;
    args << "http://www.youtube.com/watch?v=" + videoIdToLoad;
    args << QString::number(this->playerWin->winId());
    qDebug() << "start with" << args;
    //QString film = QString::fromUtf8("/home/manu/Vidéos/shrek.avi");
    //args << film;
    //QString cmd = "/usr/bin/mplayer";//  + args.join(" ");
    qDebug() << "cmd: " << cmd;
    qDebug() << "args: " << args;
    innerProcess->start(cmd,args);
    qDebug() << "launched";
    if (!innerProcess->waitForStarted(-1)){
         qDebug() << "Start failed:" << innerProcess->errorString();
         emit(failedToStart());
    }
    qDebug() << "started";
    videoIdLoading=videoIdToLoad;
    videoIdToLoad="";
}



void HandleMplayer::sendOrder(QString line){
    //qDebug() << "write" << line;
    QByteArray cmd;
    cmd.append(line).append("\n");
    innerProcess->write(cmd);
}


void HandleMplayer::readyToRead(){
    while(innerProcess->canReadLine()) {
        QString lineOut = innerProcess->readLine();
        lineOut.replace(QByteArray("'"), QByteArray(""));
        lineOut.replace(QByteArray("\""), QByteArray(""));
        lineOut.replace(QByteArray("\n"), QByteArray(""));

        //qDebug() << "readLine--"<<lineOut<<"--";
        //traitement de la sortie:


        // duration: 256 (au debut) readLine " duration: 177"
        if(lineOut.startsWith(" duration")){
            lineOut.remove(0, 11);
            this->length=lineOut.toInt();
            qDebug()<<"length:'" << length <<"'";
        }

        //get_time_pos
        //ANS_TIME_POSITION=106.2
        else if(lineOut.startsWith("ANS_TIME_POSITION=")){
            lineOut.remove(0, 17);
            //qDebug()<<"pos:-"<<lineOut<<"-";
            emit(positionChanged(lineOut));
        }

        //-- "Starting playback..." --
        else if(lineOut.startsWith("Starting")){
            emit(started(length));
            this->refreshTimer->start(1500);
        }


        //emit(outputLineChanged());
    }
}

void HandleMplayer::readyToReadError(){
    qDebug()<< "error:" << QString(innerProcess->readAllStandardError());
}

void HandleMplayer::processFinished(int exitCode, QProcess::ExitStatus exitStatus){
    this->refreshTimer->stop();
    if(videoIdToLoad.isEmpty()){
        emit(finished());
        qDebug()<<"finish and rien à lire";
        return;
    }
    this->startProcess();
}

QString HandleMplayer::videoPlaying(){
    return videoIdLoading;
}

void HandleMplayer::refreshPosition(){
    this->sendOrder("get_time_pos");
}
